<template>
  <div class="chat-window" :class="{ 'minimized': isMinimized }">
    <div class="chat-header" @click="toggleMinimize">
      <div class="header-info">
        <img src="/eggfriedrice-logo.svg" alt="蛋炒饭王国" class="logo" />
        <h3>蛋炒饭王国智能客服</h3>
        <span class="memory-id">memoryId: {{ memoryId }}</span>
      </div>
      <div class="header-actions">
        <button class="btn-minimize" @click.stop="toggleMinimize">
          {{ isMinimized ? '▶' : '▼' }}
        </button>
        <button class="btn-close" @click.stop="handleClose">
          ×
        </button>
      </div>
    </div>
    
    <div class="chat-content" v-if="!isMinimized">
      <div class="chat-messages" ref="messagesContainer" v-html="formattedMessages"></div>
      
      <div class="chat-input-area">
        <textarea
          id="chatInput"
          v-model="inputMessage"
          class="chat-input"
          placeholder="请输入您的问题..."
          @keyup.enter.ctrl="sendMessage"
          rows="3"
        ></textarea>
        <div class="input-actions">
          <span class="tip">按 Ctrl+Enter 发送</span>
          <button class="btn-send" @click="sendMessage" :disabled="!inputMessage.trim() || isSending">
            {{ isSending ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import chatService from '../utils/ChatService';

export default {
  name: 'ChatWindow',
  props: {
    memoryId: {
      type: String,
      default: '1'
    }
  },
  emits: ['close'],
  data() {
      return {
        messages: [],
        inputMessage: '',
        isSending: false,
        isMinimized: false,
        assistantTyping: false,
        memoryId: '1', // 使用固定的memoryId值，与后端示例一致
        currentCancelRequest: null
      };
    },
  computed: {
    formattedMessages() {
      return this.messages.map(msg => {
        const content = msg.content;
        if (msg.type === 'user') {
          return `
            <div class="message user-message">
              <div class="message-content">${content}</div>
              <div class="message-time">${msg.time}</div>
            </div>
          `;
        } else {
          return `
            <div class="message assistant-message">
              <div class="avatar">
                <img src="/chef-avatar.svg" alt="客服" />
              </div>
              <div class="message-body">
                <div class="message-content">${content}</div>
                <div class="message-time">${msg.time}</div>
              </div>
            </div>
          `;
        }
      }).join('');
    }
  },
  watch: {
    messages() {
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    }
  },
  mounted() {
    // 添加欢迎消息
    this.messages.push({
      type: 'assistant',
      content: '欢迎来到蛋炒饭王国！我是智能客服，请问有什么可以帮助您的？',
      time: this.formatTime(new Date())
    });
  },
  beforeUnmount() {
    chatService.closeConnection(this.memoryId);
  },
  methods: {
    sendMessage() {
      console.log('========================================');
      console.log('📤 发送消息按钮被点击');
      
      const message = this.inputMessage.trim();
      if (!message || this.isSending) {
        console.log('⚠️  消息内容为空或正在发送中，不发送');
        return;
      }

      // 取消之前可能存在的请求
      if (this.currentCancelRequest) {
        console.log('🔄 取消之前的请求');
        this.currentCancelRequest();
        this.currentCancelRequest = null;
      }

      this.isSending = true;
      this.assistantTyping = true;
      
      console.log('💬 用户消息:', message);

      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: message,
        time: this.formatTime(new Date())
      });

      this.inputMessage = '';
      
      // 记录助手消息的索引
      const assistantMessageIndex = this.messages.length;
      this.messages.push({
        type: 'assistant',
        content: '',
        time: this.formatTime(new Date())
      });

      this.scrollToBottom();
      
      console.log('📝 准备调用ChatService.sendMessage');
      console.log('🎯 MemoryId:', this.memoryId);
      
      try {
        // 保存取消函数
        const cancelRequest = chatService.sendMessage(
          this.memoryId,
          message,
          (chunk) => {
            console.log('✅ 接收到数据块:', chunk.substring(0, 30) + (chunk.length > 30 ? '...' : ''));
            // 更新助手消息内容
            this.messages[assistantMessageIndex].content += chunk;
            
            // 确保UI更新
            this.$nextTick(() => {
              this.$forceUpdate();
              this.scrollToBottom();
              console.log('🎨 UI已更新，滚动到底部');
            });
          },
          (error) => {
            console.error('❌ 发送消息失败:', error);
            // 显示详细的错误信息
            const errorMessage = error.message || '未知错误';
            this.messages[assistantMessageIndex].content = `请求失败: ${errorMessage}，请检查网络连接或稍后重试。`;
            this.isSending = false;
            this.assistantTyping = false;
            this.$forceUpdate();
          }
        );
        
        console.log('✅ 成功创建请求，保存取消函数');
        
        // 存储取消函数，以便在需要时取消请求
        this.currentCancelRequest = cancelRequest;
        
      } catch (error) {
        console.error('💥 发送消息时发生异常:', error);
        this.isSending = false;
        this.assistantTyping = false;
        this.messages[assistantMessageIndex].content = `发生异常: ${error.message}`;
        this.$forceUpdate();
      }
      
      // 立即重置发送状态（因为请求是异步的）
      this.isSending = false;
      
      console.log('📤 消息发送请求已发起，等待响应...');
      console.log('========================================');
    },
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    scrollToBottom() {
      if (this.$refs.messagesContainer) {
        this.$refs.messagesContainer.scrollTop = this.$refs.messagesContainer.scrollHeight;
      }
    },
    toggleMinimize() {
      this.isMinimized = !this.isMinimized;
      if (!this.isMinimized) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    handleClose() {
      chatService.closeConnection(this.memoryId);
      this.$emit('close', this.memoryId);
    }
  }
};
</script>

<style scoped>
/* 重置样式确保没有冲突 */
* {
  color-adjust: exact;
  -webkit-print-color-adjust: exact;
}

.chat-window {
  width: 400px;
  height: 600px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 20px;
  position: relative;
  border: 2px solid #ffb74d;
}

.chat-window.minimized {
  height: 60px;
}

.chat-header {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
  color: #000000 !important;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.logo {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
}

.header-info h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #000000 !important;
}

.memory-id {
  font-size: 12px;
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
  margin-left: 8px;
  color: #000000 !important;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.btn-minimize,
.btn-close {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: #000000 !important;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

.btn-minimize:hover,
.btn-close:hover {
  background: rgba(255, 255, 255, 0.3);
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #ffffff;
  background-image: none;
}

.message {
  margin-bottom: 16px;
  display: flex;
}

.user-message {
  justify-content: flex-end;
  flex-direction: column;
  align-items: flex-end;
}

.assistant-message {
  align-items: flex-start;
  gap: 8px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  background: #fff;
  border: 1px solid #e0e0e0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-body {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  overflow-x: auto;
}

/* 确保用户消息文字清晰 */
.user-message .message-content {
  background-color: #e3f2fd !important;
  color: #000000 !important;
  font-weight: 600 !important;
  text-shadow: none !important;
}

/* 确保助手消息文字是纯黑色且有最高优先级 */
.assistant-message .message-content {
  background-color: #ffffff !important;
  color: #000000 !important;
  border: 2px solid #e0e0e0 !important;
  border-left: 4px solid #ff9800 !important;
  font-weight: 600 !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12) !important;
  text-shadow: none !important;
  -webkit-text-fill-color: #000000 !important;
  opacity: 1 !important;
  z-index: 10 !important;
}

.message-content {
  padding: 14px 18px;
  border-radius: 18px;
  word-wrap: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  font-size: 16px !important;
  line-height: 1.8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  opacity: 1 !important;
  transition: all 0.2s ease;
}

.message-content:hover {
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
}

.message-time {
  font-size: 12px;
  color: #666666 !important;
  margin-top: 4px;
  padding: 0 4px;
  -webkit-text-fill-color: #666666 !important;
  text-shadow: none !important;
  opacity: 1 !important;
  z-index: 10 !important;
}

.chat-input-area {
  padding: 16px;
  background: #fff;
  border-top: 1px solid #e0e0e0;
}

.chat-input {
  width: 100%;
  padding: 10px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  resize: none;
  font-size: 14px;
  font-family: inherit;
  outline: none;
  transition: border-color 0.3s;
  background-color: #ffffff !important;
  color: #000000 !important;
  box-shadow: none !important;
  -webkit-text-fill-color: #000000 !important;
  caret-color: #000000 !important;
}

.chat-input:focus {
  border-color: #ff9800;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.tip {
  font-size: 12px;
  color: #999 !important;
}

.btn-send {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
  color: #000000 !important;
  border: none;
  padding: 8px 20px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: opacity 0.3s;
}

.btn-send:hover:not(:disabled) {
  opacity: 0.9;
}

.btn-send:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #ffb74d;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #ff9800;
}

/* 确保助手消息文字颜色正确且有最高优先级 */
.assistant-message .message-content,
.assistant-message .message-content * {
  color: #000000 !important;
  -webkit-text-fill-color: #000000 !important;
  text-shadow: none !important;
  opacity: 1 !important;
  z-index: 10 !important;
}

/* 直接针对textarea元素的样式 */
textarea {
  background-color: #ffffff !important;
  color: #000000 !important;
  border: 1px solid #e0e0e0 !important;
  outline: none !important;
  box-shadow: none !important;
  -webkit-text-fill-color: #000000 !important;
  opacity: 1 !important;
  caret-color: #000000 !important;
  z-index: 9999 !important;
}

</style>